package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.exception.DuplicateException;
import com.fadadianqi.goods.model.Category;
import com.fadadianqi.goods.model.Properties;
import com.fadadianqi.goods.service.GoodsService;
import com.yeqiangwei.commons.util.BeanUtils;
import com.yeqiangwei.commons.util.ParamUtils;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;

@Controller
public class PropertiesController {

    private static final String COMMAND_NAME = "command";

    @RequestMapping(value = "/a/brand-category/props/form")
    public String ajaxShowForm(HttpServletRequest request, ModelMap modelMap) {
        Category category = null;
        String propId = ParamUtils.getString(request, "pid", null);
        Properties properties = goodsService.getProperties(propId);
        if (ValidatorHelper.isEmpty(properties)) {
            String categoryId = ParamUtils.getString(request, "cid", null);
            category = goodsService.getCategoryById(categoryId);
        } else {
            modelMap.put("properties", properties);
            category = goodsService.getCategoryById(properties.getCategoryId());
        }
        modelMap.put("category", category);
        return "/admin/brand-category/propsForm";
    }

    @RequestMapping(value = "/a/brand-category/props/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxSave(@ModelAttribute(COMMAND_NAME) PropForm props
            , BindingResult result, SessionStatus status) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;
        try {
            if (props.getCopyProp()) {
                List<Category> categories = goodsService.findAllCategory();
                if (ValidatorHelper.isNotEmpty(categories)) {
                    for (Category c : categories) {
                        Properties p = new Properties();
                        BeanUtils.copyProperties(p, props);
                        p.setCategoryId(c.getId());
                        // 给所有的分类添加同一个名称的属性
                        try {
                            goodsService.saveProperties(p);
                        } catch (DuplicateException e) {
                            // 某个分类下属性添加失败的话则忽略
                        }
                    }
                }
            } else {
                goodsService.saveProperties(props);
            }
            rs = new AjaxResult(props, Boolean.TRUE, null);
        } catch (Exception e) {
            String msg = messageSource.getMessage(e.getMessage(), null, Locale.getDefault());
            rs = new AjaxResult(props, Boolean.FALSE, msg);
        }
        status.setComplete();
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/a/brand-category/props/del", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> ajaxDel(@ModelAttribute(COMMAND_NAME) Properties props
            , BindingResult result, SessionStatus status) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        AjaxResult rs = null;
        try {
            goodsService.delProperties(props);
            rs = new AjaxResult(props, Boolean.TRUE, null);
        } catch (Exception e) {
            String msg = messageSource.getMessage(e.getMessage(), null, Locale.getDefault());
            rs = new AjaxResult(props, Boolean.FALSE, msg);
        }
        status.setComplete();
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private GoodsService goodsService;

    public static class PropForm extends Properties {

        /**
         *
         */
        private static final long serialVersionUID = -686683724406800253L;

        private Boolean copyProp;

        public Boolean getCopyProp() {
            return copyProp;
        }

        public void setCopyProp(Boolean copyProp) {
            this.copyProp = copyProp;
        }
    }
}
